/**
 * Copyright (c) 2025   All rights reserved.
 *
 * https://www.sdl.io
 *
 * 版权所有，侵权必究！
 */

package io.sdl.common.xss;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

/**
 * XSS过滤
 * @authorDc 1211734836@qq.com
 */
public class XssFilter implements Filter {

	@Override
	public void init(FilterConfig config) {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		// 跳过multipart请求
		if (isMultipartRequest(httpRequest)) {
			chain.doFilter(request, response);
			return;
		}

		// 只处理非multipart请求
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(httpRequest);
		chain.doFilter(xssRequest, response);
	}

	@Override
	public void destroy() {
	}


	private boolean isMultipartRequest(HttpServletRequest request) {
		return request.getContentType() != null
				&& request.getContentType().startsWith("multipart/form-data");
	}
}
